package com.authine.cloudpivot.ext.service.impl;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.PlatformConst;
import com.authine.cloudpivot.ext.constants.WebConstants;
import com.authine.cloudpivot.ext.dto.OrderCustomerDto;
import com.authine.cloudpivot.ext.dto.OrderCustomerGoodsDto;
import com.authine.cloudpivot.ext.dto.api.BulkRefundVO;
import com.authine.cloudpivot.ext.dto.system.OrganizationDto;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.entity.order.extendsAttr.OrderCustomerExtendsAttr;
import com.authine.cloudpivot.ext.entity.order.extendsAttr.OrderGoodsExtendsAttr;
import com.authine.cloudpivot.ext.enums.OrderGoodsStatusV1Enum;
import com.authine.cloudpivot.ext.enums.commoditymaterials.GoodsPurchaseTypeEnum;
import com.authine.cloudpivot.ext.enums.order.*;
import com.authine.cloudpivot.ext.enums.system.OrganizationAttributeEnum;
import com.authine.cloudpivot.ext.eum.CustomerOrderStatusV1Enum;
import com.authine.cloudpivot.ext.model.order.*;
import com.authine.cloudpivot.ext.service.OrderCustomerBaseV1Service;
import com.authine.cloudpivot.ext.service.OrderService;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.cloudpivot.ext.utils.system.*;
import com.authine.cloudpivot.ext.vo.*;
import com.authine.cloudpivot.ext.vo.i.IOrderCustomerVO;
import com.authine.common.json.JsonUtils;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.utils.JsonParseObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.assertj.core.util.Lists;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: liwei
 * @DateTime: 2021/9/4
 * @Description: TODO
 */
@Slf4j
public class OrderCustomerBaseV1ServiceImpl implements OrderCustomerBaseV1Service {
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    private final TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);
    BigDecimal difference = new BigDecimal("0.000001");
    private OrderService orderService = new OrderServiceImpl();


    @Override
    public BOList listBoAllContainMemberIds(OrderCustomerDto dto) {

        log.info("------------------------全部列表分页查询 listBoAllContainMemberIds Param：{}------------------------", JsonUtils.toJson(dto));
        if (null == dto.getPageIndex()) {
            dto.setPageIndex(WebConstants.DEF_PAGE);
        }

        if (null == dto.getPageSize() || dto.getPageSize() > 100) {
            dto.setPageSize(WebConstants.DEF_SIZE);
        }

        String tableName = getTableName(ModelConst.T_ORDER_CUSTOMER);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from " + tableName + " where deleted ='0' ");
        countSql.append("select count(*) from " + tableName + " where deleted ='0' ");

        //拼接参数
        if (!CollectionUtils.isEmpty(dto.getIds())) {
            whereSql.append(" AND id in (:ids) ");
            parameter.put("ids", dto.getIds());
        }
        if (!CollectionUtils.isEmpty(dto.getPlaceOrderUserIdList())) {
            whereSql.append(" AND JSON_UNQUOTE(place_order_user_id->'$.id') IN (:placeOrderUserIds) ");
            parameter.put("placeOrderUserIds", dto.getPlaceOrderUserIdList());
        }
        if (StringUtils.isNotBlank(dto.getErpPO())) {
            List<String> erpPo = StringUtils.stringToListString(dto.getErpPO(), ";");
            whereSql.append(" AND erp_po IN (:erp_po) ");
            parameter.put("erp_po", erpPo);
        }

        if (StringUtils.isNotBlank(dto.getReceiver())) {
            whereSql.append(" AND receiver LIKE :receiver ");
            parameter.put("receiver", "%" + dto.getReceiver() + "%");
        }
        if (StringUtils.isNotBlank(dto.getPhone())) {
            whereSql.append(" AND phone LIKE :phone ");
            parameter.put("phone", "%" + dto.getPhone() + "%");
        }

        if (StringUtils.isNotBlank(dto.getAddress())) {
            whereSql.append(" AND address LIKE :address ");
            parameter.put("address", "%" + dto.getAddress() + "%");
        }
        //todo 新老状态转换
        if (null != dto.getCustomerOrderStatusV1Enum()) {
            CustomerOrderStatusV1Enum customerOrderStatusV1Enum = dto.getCustomerOrderStatusV1Enum();
            if (customerOrderStatusV1Enum == CustomerOrderStatusV1Enum.NEW) {
                //新建 =》未付款 & label：审批中
                //todo label
                whereSql.append(" AND order_customer_status =:status ");
                parameter.put("status", OrderCustomerStatusEnum.UpcomingPayment.name());
            }
            if (customerOrderStatusV1Enum == CustomerOrderStatusV1Enum.PAYMENT) {
                //待付款 =》未付款 & label!=审批中
                //todo label
                whereSql.append(" AND order_customer_status =:status ");
                parameter.put("status", OrderCustomerStatusEnum.UpcomingPayment.name());
            }
            if (customerOrderStatusV1Enum == CustomerOrderStatusV1Enum.PAID) {
                //已付款 =》未接单 | 未发货 | 已发货
                whereSql.append(" AND order_customer_status IN ( :statusList ) ");
                parameter.put("statusList", Lists.newArrayList(OrderCustomerStatusEnum.UpcomingConfirm.name(), OrderCustomerStatusEnum.UpcomingDelivery.name(), OrderCustomerStatusEnum.DoneDelivery.name()));
            }
            if (customerOrderStatusV1Enum == CustomerOrderStatusV1Enum.RETURN) {
                //退货 =》售后状态=售后中
                whereSql.append(" AND order_customer_status =:status AND after_sale = :afterSale ");
                parameter.put("status", OrderCustomerStatusEnum.UpcomingPayment.name());
                parameter.put("afterSale", PlatformConst.AFTER_SALES);
            }
            if (customerOrderStatusV1Enum == CustomerOrderStatusV1Enum.CANCEL) {
                //取消 =》已关闭
                whereSql.append(" AND order_customer_status =:status ");
                parameter.put("status", OrderCustomerStatusEnum.Closed.name());
            }
            if (customerOrderStatusV1Enum == CustomerOrderStatusV1Enum.DONE) {
                //已完成 =》已完成
                whereSql.append(" AND order_customer_status =:status ");
                parameter.put("status", OrderCustomerStatusEnum.Done.name());
            }
            if (customerOrderStatusV1Enum == CustomerOrderStatusV1Enum.REJECTED) {
                //已驳回 =》未付款 & label：审批驳回
                //todo label
                whereSql.append(" AND order_customer_status =:status ");
                parameter.put("status", OrderCustomerStatusEnum.UpcomingPayment.name());
            }
        }

        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" ORDER BY id DESC");
        listSql.append(" LIMIT " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------分页查询客户订单 listBoAllContainMemberIds listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------分页查询客户订单 listBoAllContainMemberIds whereSql：{}------------------------parameter：{}", whereSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        for (Map<String, Object> map : resultList) {
            if (null != map.get("extends_attr") && !map.get("extends_attr").equals("")) {
                Map<String, Object> extendsAttr = (Map) JSONObject.parse((String) map.get("extends_attr"));
                String approvalBy = (String) extendsAttr.get("approvalBy");
                String approvalOpinion = (String) extendsAttr.get("approvalOpinion");
                map.put("approval_by", approvalBy);
                map.put("approval_opinion", approvalOpinion);
            }
        }
        //构建结果集
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_CUSTOMER);
        return bOList;
    }

    @Override
    public BOList listOrderCustomerGoodsContainMemberIds(OrderCustomerGoodsDto dto) {
        log.info("------------------------客户分页查询订单商品 listOrderCustomerGoodsContainMemberIds Param：{}------------------------", JsonUtils.toJson(dto));

        if (null == dto.getPageIndex()) {
            dto.setPageIndex(WebConstants.DEF_PAGE);
        }

        if (null == dto.getPageSize() || dto.getPageSize() > 100) {
            dto.setPageSize(WebConstants.DEF_SIZE);
        }

        String customerGoodsTableName = getTableName(ModelConst.T_ORDER_CUSTOMER_GOODS);
        String customerTableName = getTableName(ModelConst.T_ORDER_CUSTOMER);
        String vendorTableName = getTableName(ModelConst.T_ORDER_VENDOR);
        String goodsReturnsTableName = getTableName(ModelConst.T_ORDER_GOODS_RETURNS);

        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("SELECT * FROM " + customerGoodsTableName + " cg ");
        listSql.append(" LEFT JOIN " + customerTableName + " c ON cg.order_customer_id = c.id ");
        listSql.append(" LEFT JOIN " + vendorTableName + " v ON cg.order_vendor_id = v.id WHERE cg.deleted ='0' ");
        countSql.append("SELECT COUNT(*) FROM " + customerGoodsTableName + " cg ");
        countSql.append(" LEFT JOIN " + customerTableName + " c ON cg.order_customer_id = c.id ");
        countSql.append(" LEFT JOIN " + vendorTableName + " v ON cg.order_vendor_id = v.id WHERE cg.deleted ='0' ");

        //拼接参数
        if (!CollectionUtils.isEmpty(dto.getIds())) {
            whereSql.append(" AND cg.id in (:ids) ");
            parameter.put("ids", dto.getIds());
        }

        if (!CollectionUtils.isEmpty(dto.getOrderCustomerIds())) {
            whereSql.append(" AND cg.order_customer_id in (:orderCustomerIds) ");
            parameter.put("orderCustomerIds", dto.getOrderCustomerIds());
        }

        if (!CollectionUtils.isEmpty(dto.getOrderVendorIds())) {
            whereSql.append(" AND cg.order_vendor_id in (:orderVendorIds) ");
            parameter.put("orderVendorIds", dto.getOrderVendorIds());
        }

        if (StringUtils.isNotBlank(dto.getBrand())) {
            whereSql.append(" AND cg.brand LIKE :brand ");
            parameter.put("brand", "%" + dto.getBrand() + "%");
        }
        if (StringUtils.isNotBlank(dto.getName())) {
            whereSql.append(" AND cg.`name` LIKE :name ");
            parameter.put("name", "%" + dto.getName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getModel())) {
            whereSql.append(" AND cg.model LIKE :model ");
            parameter.put("model", "%" + dto.getModel() + "%");
        }
        if (StringUtils.isNotBlank(dto.getSpec())) {
            whereSql.append(" AND cg.spec LIKE :spec ");
            parameter.put("spec", "%" + dto.getSpec() + "%");
        }

        // todo 权限问题
        // 新老状态转换
        if (null != dto.getOrderGoodsStatusV1Enum()) {
            OrderGoodsStatusV1Enum orderGoodsStatusV1Enum = dto.getOrderGoodsStatusV1Enum();

            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.NEW) {
                //新建 ==》未付款 & 客户订单表 label：审批中
                whereSql.append(" AND cg.order_customer_goods_status = :orderVendorStatus AND c.label LIKE '%:label%' ");
                parameter.put("orderVendorStatus", OrderGoodsStatusEnum.UpcomingPayment.name());
                parameter.put("label", OrderApproveStatusEnum.APPROVING.id);
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.SUBMIT) {
                //待付款 =》未付款 & 客户订单表 label!=审批中
                whereSql.append(" AND cg.order_customer_goods_status = :orderVendorStatus AND c.label NOT LIKE '%:label%' OR c.label IS NULL ");
                parameter.put("orderVendorStatus", OrderGoodsStatusEnum.UpcomingPayment.name());
                parameter.put("label", OrderApproveStatusEnum.APPROVING.id);
            }

            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.PAYED) {
                // 待出库（待发货） =》未接单
                whereSql.append(" AND cg.order_customer_goods_status = :orderVendorStatus ");
                parameter.put("orderVendorStatus", OrderGoodsStatusEnum.UpcomingConfirm.name());
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.PACKAGING) {
                //待发货（出库中） =》未发货 & 已发货数量 = 0
                whereSql.append(" AND cg.order_customer_goods_status = :orderVendorStatus AND cg.quantity_shipped = '0' ");
                parameter.put("orderVendorStatus", OrderGoodsStatusEnum.UpcomingDelivery.name());
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.DELIVERED) {
                //待收货（已发货） =》已发货
                whereSql.append(" AND cg.order_customer_goods_status = :orderVendorStatus ");
                parameter.put("orderVendorStatus", OrderGoodsStatusEnum.DoneDelivery.name());
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.TO_RETURN) {
                // 待退货 =》label：待退货（客户退货）
                whereSql.append(" AND cg.label LIKE '%:goods_label%' ");
                parameter.put("goods_label", OrderApproveStatusEnum.TO_RETURN.id);
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.RETURNING) {
                // 退货中 =》label：退货中（供应商审批中）
                whereSql.append(" AND cg.label LIKE '%:goods_label%' ");
                parameter.put("goods_label", OrderApproveStatusEnum.RETURNING.id);
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.REFUNDING) {
                // 退款中 =》label：退款中（供应商审批中）
                whereSql.append(" AND cg.label LIKE '%:goods_label%' ");
                parameter.put("goods_label", OrderApproveStatusEnum.REFUNDING.id);
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.RETIRED) {
                // 已退货 =》label：已退货（供应商收货）
                whereSql.append(" AND cg.label LIKE '%:goods_label%' ");
                parameter.put("goods_label", OrderApproveStatusEnum.RETIRED.id);
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.DONE) {
                //已完成 =》已完成
                whereSql.append(" AND cg.order_customer_goods_status = :orderVendorStatus ");
                parameter.put("orderVendorStatus", OrderGoodsStatusEnum.Done.name());
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.CLOSED) {
                //已关闭 =》已关闭& 退款退货数量=0
                whereSql.append(" AND cg.order_customer_goods_status = :orderVendorStatus AND ( SELECT count(*) FROM " + goodsReturnsTableName + " odr WHERE odr.`order_goods_returns_status` not in ( :goodsReturnsStatusList ) AND odr.order_customer_goods_id = cg.id ) = '0' ");
                parameter.put("orderVendorStatus", OrderGoodsStatusEnum.Closed.name());
                parameter.put("goodsReturnsStatusList", Lists.newArrayList(OrderGoodsReturnsStatusEnum.Done.name(), OrderGoodsReturnsStatusEnum.Closed.name()));

            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.REFUND_APPLICATION) {
                //退款申请中 =》label：退款申请中（平台审批中）
                whereSql.append(" AND cg.label LIKE  '%:goods_label%' ");
                parameter.put("goods_label", OrderApproveStatusEnum.REFUND_APPLICATION.id);
            }
            if (orderGoodsStatusV1Enum == OrderGoodsStatusV1Enum.RETURNED) {
                //已退款 = 》已关闭 & 退款退货数量=商品总数量
                whereSql.append(" AND cg.order_customer_goods_status = :orderVendorStatus AND ( SELECT SUM(odr.quantity) FROM " + goodsReturnsTableName + " odr WHERE odr.`order_goods_returns_status`  = :goodsReturnsStatus  AND odr.order_customer_goods_id = cg.id ) = cg.quantity ");
                parameter.put("orderVendorStatus", OrderGoodsStatusEnum.Closed.name());
                parameter.put("goodsReturnsStatus", OrderGoodsReturnsStatusEnum.Done.name());
            }
        }

        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" ORDER BY cg.id DESC");
        listSql.append(" LIMIT " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------客户分页查询订单商品 listOrderCustomerGoodsContainMemberIds listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------客户分页查询订单商品 listOrderCustomerGoodsContainMemberIds whereSql：{}------------------------parameter：{}", whereSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);

        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORDER_CUSTOMER_GOODS);
        return bOList;
    }

    @Override
    public List<OrderGoodsV1VO> transferOrderCustomerGoodsV1VOList(BOList boList) {

        if (null == boList || 0 == boList.getTotal() || null == boList.getData()) {
            return null;
        }

        List<String> relationIdList = boList.getData().stream().map(e -> String.valueOf(e.get("relation_id"))).collect(Collectors.toList());
        List<String> orderCustomerIdList = boList.getData().stream().map(e -> String.valueOf(e.get("order_customer_id"))).collect(Collectors.toList());
        //List<String> orderVendorIdList = boList.getData().stream().map(e -> String.valueOf(e.get("order_vendor_id"))).collect(Collectors.toList());

        List<Map<String, Object>> customerOrderList = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER).selectField("*").in("id", orderCustomerIdList).queryForList();
        Assert.isTrue(!CollectionUtils.isEmpty(customerOrderList), "查询客户订单商品信息 不能为空");

        List<Map<String, Object>> goodsRelationList = JdbcTemplateUtils.builder(ModelConst.T_ORDER_GOODS_RELATION).selectField("*").in("id", relationIdList).queryForList();

        Map<String, Map<String, Object>> relationMap = null;
        if (!CollectionUtils.isEmpty(goodsRelationList)) {
            relationMap = goodsRelationList.stream().collect(Collectors.toMap(e -> String.valueOf(e.get("id")), ogr -> ogr));

        }

        Map<String, Map<String, Object>> customerOderMap = customerOrderList.stream().collect(Collectors.toMap(e -> String.valueOf(e.get("id")), ogr -> ogr));

        List<OrderGoodsV1VO> orderGoodsV1VOList = new LinkedList<>();

        for (Map<String, Object> orderCustomerGoods : boList.getData()) {

            Map<String, Object> relation = null == relationMap ? null : relationMap.getOrDefault(String.valueOf(orderCustomerGoods.get("relation_id")), null);

            Map<String, Object> customerOder = customerOderMap.getOrDefault(String.valueOf(orderCustomerGoods.get("order_customer_id")), null);

            Map<String, Object> inquiry = null;
            if (null != relation) {
                //询价
                String inquiryId = String.valueOf(relation.get("inquiry_id"));
                inquiry = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_INQUIRY).selectField("*").eq("id", inquiryId).queryForMap();
            }

            //报价
            Map<String, Object> quotationGoods = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_QUOTATION_GOODS).selectField("*").eq("id", orderCustomerGoods.get("goods_id")).queryForMap();


            OrderGoodsV1VO orderGoodsV1VO = OrderGoodsV1VO.of().setOrderGoodsId(String.valueOf(orderCustomerGoods.get("id")))
                    .setClientOrderGoodsId(String.valueOf(orderCustomerGoods.get("client_order_goods_id")))
                    .setCustomerOrderId(String.valueOf(orderCustomerGoods.get("order_customer_id")))
                    .setVendorOrderId(String.valueOf(orderCustomerGoods.get("order_vendor_id")))
                    .setVendorName(String.valueOf(orderCustomerGoods.get("vendor_organization_name")))
                    .setName(String.valueOf(orderCustomerGoods.get("name")))
                    .setBrand(String.valueOf(orderCustomerGoods.get("brand")))
                    .setModel(String.valueOf(orderCustomerGoods.get("model")))
                    .setSpec(String.valueOf(orderCustomerGoods.get("spec")))
                    .setSku(String.valueOf(orderCustomerGoods.get("sku")))
                    .setBarCode(String.valueOf(orderCustomerGoods.get("bar_code")))
                    .setUnspsc(String.valueOf(orderCustomerGoods.get("unspsc")))
                    .setGoldenTax(String.valueOf(orderCustomerGoods.get("golden_tax")))
                    .setImages(String.valueOf(orderCustomerGoods.get("images")))
                    .setDescription(String.valueOf(orderCustomerGoods.get("description")))
                    .setTechnical(String.valueOf(orderCustomerGoods.get("technical")))
                    .setPackaging(String.valueOf(orderCustomerGoods.get("packaging")))
                    .setMemo(String.valueOf(orderCustomerGoods.get("memo")))
                    .setUnit(String.valueOf(orderCustomerGoods.get("unit")))
                    .setPackageUnit(String.valueOf(orderCustomerGoods.get("package_unit")))
                    .setNum(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("quantity")))
                    .setPackageNum(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("package_quantity")))
                    .setDelivery(BigDecimalUtils.bigDecimalToInteger(orderCustomerGoods.get("delivery")))
                    .setTaxRate(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("tax_rate")))
                    .setTaxRateFreight(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("freight_rate")))
                    .setPretaxPrice(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("pretax_price")))
                    .setPrice(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("price")))
                    .setPretaxFreight(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("pretax_freight")))
                    .setFreight(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("freight")))
                    .setPretaxTotal(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("pretax_total")))
                    .setTotal(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("total")))
                    .setPretaxAmount(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("pretax_amount")))
                    .setAmount(BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("amount")))
                    .setStatus(String.valueOf(orderCustomerGoods.get("order_vendor_goods_status")))
                    .setAttachment(String.valueOf(orderCustomerGoods.get("attachment")))
                    .setOrderType(String.valueOf(customerOder.get("type")))
                    .setCustomerOrgName(String.valueOf(orderCustomerGoods.get("customer_organization_name")))
                    .setMemberName(String.valueOf(customerOder.get("place_order_fullname"))) //实际下单人？
                    .setTime(Utils.strToDate(String.valueOf(customerOder.get("createdTime"))))
                    .setClarifyTips(quotationGoods == null ? null : String.valueOf(quotationGoods.get("clarify_tips")))
                    .setCategory(String.valueOf(orderCustomerGoods.get("category")))
                    .setRemarkMessages(quotationGoods == null ? null : String.valueOf(quotationGoods.get("remark_message")))
                    .setQuotationGoodsId(String.valueOf(orderCustomerGoods.get("goods_id")))
                    .setDemandDeptName(inquiry == null ? null : String.valueOf(inquiry.get("department_name")))
                    .setInquiryMemberName(inquiry == null ? null : String.valueOf(inquiry.get("member_name")));

            orderGoodsV1VOList.add(orderGoodsV1VO);
        }

        return orderGoodsV1VOList;
    }

    @Override
    public List<Map<String, Object>> findAllByClientOrderId(String clientOrderId, String clientId) {

        Assert.isTrue(!(StringUtils.isBlank(clientOrderId) || StringUtils.isBlank(clientId)), "参数不能为空");

        return JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER).selectField("*").eq("client_order_id", clientOrderId)
                .eq("client_id", clientId).queryForList();
    }


    @Override
    public void createCustomerOrder(Map<String, Object> orderCustomer, UserDto userDto) {
        String orgId = userDto.getOrganization_id().get(0).getId();
        OrganizationDto organizationDto = OrgUtils.getOrgByOrgId(orgId);

        Assert.isTrue(null != organizationDto, "用户组织不可用!");

        Assert.isTrue(CollectionUtils.isNotEmpty(organizationDto.getTransaction_organization_id()), "请联系平台管理员添加客户结算组织!");


        if (OrgAttributeUtils.isEnabledAttribute(orgId, OrganizationAttributeEnum.OVERDUE_BUT_NOT_INVOICED)) {

            List<OrganizationDto> organizationDtoList = OrgUtils.getOrgListByOrgId(orgId);

            Assert.isTrue(CollectionUtils.isNotEmpty(organizationDtoList), "获取的ID列表为空!");

            List<String> organizationIds = organizationDtoList.stream().map(e -> e.getId()).collect(Collectors.toList());
            //t_bill TradeDirection
            //todo TradeDirection
            List<Map<String, Object>> billList = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_BILL).selectField("*")
                    .in("organization_id -> &id", organizationIds).eq("direction", "Sale").queryForList();

            Assert.isTrue(CollectionUtils.isNotEmpty(billList), "获取账单列表为空!");

            //t_trade
            List<String> tradeIdList = billList.stream().map(e -> String.valueOf(e.get("trade_id"))).collect(Collectors.toList());
            List<Map<String, Object>> tradeList = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_TRADE).selectField("*").in("id", tradeIdList).queryForList();

            Date now = new Date();
            Date delivery = null;
            for (Map<String, Object> bill : billList) {
                Date billDate = Utils.strToDate(String.valueOf(bill.get("bill_date")));
                Instant instant = billDate.toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                delivery = Date.from(instant.atZone(zoneId).toLocalDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
                int day = (int) ((now.getTime() - delivery.getTime()) / (1000 * 3600 * 24));
                Assert.isTrue(day <= 30, "部分商品已收货超30天，仍未申请开票,请前往申票，否则无法创建订单！");
            }

        }

        OrganizationDto tranOrg = organizationDto;
        if (!organizationDto.getId().equals(organizationDto.getTransaction_organization_id().get(0).getId())) {
            OrganizationDto organizationTransactionDto = OrgUtils.getOrgByOrgId(organizationDto.getTransaction_organization_id().get(0).getId());

            Assert.isTrue(null != organizationTransactionDto, "未获取到对应的结算组织！");

            tranOrg = organizationTransactionDto;
        }

        Assert.isTrue(null != tranOrg.getAccount_id(), "结算组织账户不能为空，请联系管理员添加结算组织账户！");

        //客户账期
        Assert.isTrue(null != tranOrg.getStatement_cycle() && tranOrg.getStatement_cycle() > 0, "请联系平台管理员添加客户账期！");
        Integer cap = tranOrg.getStatement_cycle();

        //校验参数
        //checkOrder(orderCustomer);

        //设置客户订单属性->客户下单客户订单状态为待付款
        //todo label 待付款 =》未付款 & label!=审批中
        orderCustomer.put("order_customer_status", OrderCustomerStatusEnum.UpcomingPayment);

        //customerOrder.setAccountPeriod(cap);

        //source
        if (null == orderCustomer.get("type")) {
            orderCustomer.put("type", OrderTypeEnum.PurchaseOrder);
        }

        //todo 客户查询被邀请的供应商组织 在个人中心 t_organization_invite_code
        List<String> vendorIds = new ArrayList<>();

        //orderVendorList
        List<Map<String, Object>> vendorOrderList = (List<Map<String, Object>>) orderCustomer.get("orderVendorList");
        //默认不是代购
        boolean ifContract = false;
        //循环设置供应商订单商品信息
        for (Map<String, Object> vendorOrder : vendorOrderList) {
            //客户下单 ->供应商订单状态为新建  新建 =》未付款
            vendorOrder.put("order_vendor_status", OrderVendorStatusEnum.UpcomingPayment);
            // 获取供应商账期
            OrganizationDto vendorOrg = OrgUtils.getOrgByOrgId(String.valueOf(vendorOrder.get("organization_id")));

            Assert.isTrue(CollectionUtils.isNotEmpty(vendorOrg.getTransaction_organization_id()), "请联系平台管理员添加供应商结算组织!(1)");

            OrganizationDto accountOrganization = OrgUtils.getOrgByOrgId(vendorOrg.getTransaction_organization_id().get(0).getId());

            Assert.isTrue(null != accountOrganization, "请联系平台管理员添加供应商结算组织!(2)");

            Assert.isTrue(null != accountOrganization.getStatement_cycle(), "请联系平台管理员添加供应商结算账期！");

            Integer vap = accountOrganization.getStatement_cycle();

            vendorOrder.put("organization_name", vendorOrg.getName());
            //vendorOrder.setAccountPeriod(vap);

            //todo 这里是结算信息状态 是否还需要？
            //vendorOrder.setReconciliationStatus(ReconciliationStatusEnum.UNDO);
            //vendorOrder.setInvoiceStatus(InvoiceStatusEnum.UNDO);
            // vendorOrder.setPaymentStatus(PaymentStatusEnum.UNDO);

            vendorOrder.put("orderCustomer", orderCustomer);

            //邀请供应商为空或者不包含当前供应商则为平台供应商 todo 新的模型 organization_type 供应商组织类型
            //vendorOrder.setPlatform(!CollectionUtils.isEmpty(vendorIds) && vendorIds.contains(vendorOrder.getVendorId()));

            // 校验订单商品 orderGoods
            Assert.isTrue(null != vendorOrder.get("orderGoods"), "供应商订单商品错误！");

            //循环设置订单商品信息
            Map<String, Object> orderGoods = (Map<String, Object>) vendorOrder.get("orderGoods");

            Assert.isTrue(null != vendorOrder.get("quantity") && BigDecimalUtils.bigDecimalToInteger(vendorOrder.get("quantity")) > 0, "订单商品数量错误！");
            GoodsSrcEnum goodsSrcEnum = (GoodsSrcEnum) orderGoods.get("goods_src");
            //goods_src
            boolean isPurchase = goodsSrcEnum == GoodsSrcEnum.SourcingSingle || goodsSrcEnum == GoodsSrcEnum.SourcingLoop;
            //客户下单 ->订单商品状态为待付款
            // todo 待付款 =》未付款 & label!=审批中
            orderGoods.put("order_vendor_goods_status", OrderGoodsStatusEnum.UpcomingPayment);
            orderGoods.put("vendor_account_period", vap);
            orderGoods.put("customer_account_period", cap);
            //orderGoods.setCustomerAccountPeriod(cap);
            //orderGoods.setVendorAccountPeriod(vap);
            orderGoods.put("returned_num", BigDecimal.ZERO);
            orderGoods.put("return_received_num", BigDecimal.ZERO);

            if (null == orderGoods.get("technical")) orderGoods.put("technical", "");
            if (null == orderGoods.get("packaging")) orderGoods.put("packaging", "");
            if (null == orderGoods.get("memo")) orderGoods.put("memo", "");
            if (null == orderGoods.get("warranty")) orderGoods.put("warranty", "");
            if (null == orderGoods.get("bar_code")) orderGoods.put("bar_code", "");
            if (null == orderGoods.get("attachment")) orderGoods.put("attachment", "");
            if (null == orderGoods.get("golden_tax")) orderGoods.put("golden_tax", "");
            if (null == orderGoods.get("unspsc")) orderGoods.put("unspsc", "");
            if (null == orderGoods.get("delivery")) orderGoods.put("delivery", 0);

            //根据业务数据分析逻辑这里省略了部分无效逻辑代码

            if (isPurchase) {
                //根据 组织采购表id 查询组织采购数据
                Map<String, Object> goodsPurchase = JdbcTemplateUtils.builder(AppConst.COMMODITYMATERIALS, ModelConst.T_GOODS_PURCHASE).selectField("*").eq("id", orderGoods.get("goods_id")).queryForMap();

                Assert.isTrue(null != goodsPurchase, "订单商品不存在！");

                Date expire = Utils.strToDate(String.valueOf(goodsPurchase.get("expire")));

                Assert.isTrue(expire.getTime() >= System.currentTimeMillis(), "商品已过期，请重新询价！");


                Map<String, Object> quotationGoodsEntity;
                //循环采购不限制采购权限
                if (goodsSrcEnum == GoodsSrcEnum.SourcingSingle) {

                    //需要校验权限

                    List<String> memberIds = UserUtils.listSubMemberIds(userDto.getId());

                    String inquiryT = JdbcTemplateUtils.getTableName(ModelConst.T_INQUIRY, AppConst.SOURCING_CENTER);
                    String quotationGoodsT = JdbcTemplateUtils.getTableName(ModelConst.T_QUOTATION_GOODS, AppConst.SOURCING_CENTER);
                    String inquiryGoodsT = JdbcTemplateUtils.getTableName(ModelConst.T_INQUIRY_GOODS, AppConst.SOURCING_CENTER);

                    //inquiry_goods_id
                    StringBuilder st = new StringBuilder(" SELECT q.* FROM ");
                    st.append(quotationGoodsT);
                    st.append(" q LEFT JOIN  ");
                    st.append(inquiryGoodsT);
                    st.append(" ig  ON  q.inquiry_goods_id = ig.id LEFT JOIN  ");
                    st.append(inquiryT);
                    st.append(" i  ON  i.id = ig.inquiry_id  ");
                    st.append(" WHERE q.id = :quotationGoodsId  ");

                    Map<String, Object> queryParam = new HashMap<>();
                    queryParam.put("quotationGoodsId", goodsPurchase.get("quotation_goods_id"));

                    if (CollectionUtils.isNotEmpty(memberIds)) {
                        st.append(" AND JSON_UNQUOTE(i.member_id -> '$.id') IN ( :memberIds ) ");
                        queryParam.put("memberIds", memberIds);
                    }

                    List<Map<String, Object>> goodsPurchaseList = JdbcTemplateUtils.queryForList(st.toString(), queryParam);

//                    if (null != memberIds && !memberIds.contains(memberId)) {
//                        log.error("{} {} {} {} ", "getQuotationGoods()", "超出权限查看", "操作人能操作的用户ids:"
//                                + memberIds + " 所操作的商品所属的用户ids:" + memberId, sessionUser.getCurrentUserID());
//                        throw new InquiryException("查看报价商品失败：询价商品不在可操作权限内");
//                    }
                    Assert.isTrue(CollectionUtils.isNotEmpty(goodsPurchaseList), "查看报价商品失败：询价商品不在可操作权限内！or 询价商品没数据！");

                    quotationGoodsEntity = goodsPurchaseList.get(0);
                } else {
                    //不需要校验权限
                    quotationGoodsEntity = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_QUOTATION_GOODS).selectField("*").eq("id", goodsPurchase.get("quotation_goods_id")).queryForMap();
                }

                Assert.isTrue(null != quotationGoodsEntity, "未获取到报价商品，暂无采购权限!");

                //询价单
                Map<String, Object> inquiryGoodsEntity = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_INQUIRY_GOODS).selectField("*").eq("id", quotationGoodsEntity.get("inquiry_goods_id")).queryForMap();
                Assert.isTrue(null != inquiryGoodsEntity, "未获取到询价单!");

                Map<String, Object> inquiryEntity = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_INQUIRY).selectField("*").eq("id", inquiryGoodsEntity.get("inquiry_id")).queryForMap();
                Assert.isTrue(null != inquiryEntity, "未获取到询价单!");

                //采购商品账期取询价单的账期
                orderGoods.put("customer_account_period", inquiryGoodsEntity.get("inquiryGoodsEntity"));
                orderGoods.put("client_order_vendor_goods_id", quotationGoodsEntity.get("client_vendor_goods_id"));
            }
        }


        //todo 保存新建订单 需要重新走一遍
        //customerOrder = iCustomerOrderRepository.save(customerOrder);

    }


    @Override
    public String verifyOrderSimple(Map<String, Object> query) {

        StringBuilder st = new StringBuilder();
        if (null == query.get("clientUserId")) {
            st.append("外部用户ID 不能为空,\n");
        }

        if (null == query.get("clientOrderId")) {
            st.append("外部订单ID 不能为空,\n");
        }

        if (null == query.get("receiver")) {
            st.append("收货人 不能为空,\n");
        }

        if (null == query.get("phone")) {
            st.append("电话 不能为空,\n");
        }

        if (null == query.get("address")) {
            st.append("地址 不能为空,\n");
        }

        if (null == query.get("orderGoodsList")) {
            st.append("订单商品集合 不能为空,\n");
        }

        if (st.length() > 0) {
            return st.toString();
        }

        log.info("orderGoodsList:{}", query.get("orderGoodsList"));

        Assert.isTrue(null != query.get("orderGoodsList"), " 订单商品参数不能为空! ");

        List<OrderGoodsSimple> orderGoodsSimpleList = JsonParseObject.parseObject(JSON.toJSONString(query.get("orderGoodsList")), OrderGoodsSimple.class);
        ;

        for (OrderGoodsSimple orderGoodsSimple : orderGoodsSimpleList) {

            if (StringUtils.isBlank(orderGoodsSimple.getSku())) {
                st.append("客户料号 不能为空,\n");
            }

            if (StringUtils.isBlank(orderGoodsSimple.getCompany())) {
                st.append("公司 不能为空,\n");
            }
        }
        return st.toString();
    }

    @Override
    public OrderCustomerVO adaptationSimpleToVO(OrderSimple orderSimple, SessionUser sessionUser) {

        OrderCustomerVO orderCustomerVO = new OrderCustomerVO();
        orderCustomerVO.setPhone(orderSimple.getPhone());
        orderCustomerVO.setReceiver(orderSimple.getReceiver());
        orderCustomerVO.setAddress(orderSimple.getAddress());
        orderCustomerVO.setClient_order_id(orderSimple.getClientOrderId());
        orderCustomerVO.setClient_user_id(orderSimple.getClientUserId());
        orderCustomerVO.setActual_order(orderSimple.getActualOrder());
        orderCustomerVO.setErp_po(orderSimple.getErpPO());

        List<OrderGoodsSimple> orderGoodsSimpleList = orderSimple.getOrderGoodsList();

        //获取牧原区域对照表中的固买收货信息
        Set<String> companySet = orderGoodsSimpleList.stream().map(OrderGoodsSimple::getCompany).collect(Collectors.toSet());
        //获取当前用户组织信息
        List<UserDto> userList = UserUtils.getOrganizationUserByRoleName(sessionUser.getCurrentOrgID(), PlatformConst.ROLE_CUSTOMER_COMPANY_REGION);
        Assert.isTrue(CollectionUtils.isNotEmpty(userList), "未获取到角色ROLE_CUSTOMER_COMPANY_REGION的用户");

        //查询会员收货地址
        List<Map<String, Object>> deliverAddressList = JdbcTemplateUtils.builder(AppConst.PERSONAL_CENTER, ModelConst.T_MEMBER_DELIVER_ADDRESS).selectField("*").eq("member_id", userList.get(0).getId())
                .in("alias", companySet).queryForList();

        Assert.isTrue(CollectionUtils.isNotEmpty(deliverAddressList), "请维护公司区域对照表信息");

        Assert.isTrue(deliverAddressList.stream().map(t -> String.valueOf(t.get("post")).trim()).distinct().count() == 1, "根据公司获取区域必须唯一");

        //拿到最新的地址
        Map<String, Object> address = deliverAddressList.stream().max(Comparator.comparing(e -> String.valueOf(e.get("id")))).get();
        Assert.isTrue(null != address.get("post"), "区域不能为空");

        orderCustomerVO.setAddress(String.valueOf(address.get("address")));
        orderCustomerVO.setReceiver(String.valueOf(address.get("receiver_name")));
        orderCustomerVO.setPhone(String.valueOf(address.get("mobile")));


        //牧原下单需要把实际收货人setup给实际下单人
        if ("mysp_api".equals(sessionUser.getCurrentClientID())) {
            //orderVo.setActualOrder(param.getReceiver());
            orderCustomerVO.setActual_order(orderSimple.getReceiver());
        }

        Map<String, Object> extendsAttr = new HashMap<>();

        extendsAttr.put("address", orderSimple.getAddress());
        extendsAttr.put("receiver", orderSimple.getReceiver());
        extendsAttr.put("phone", orderSimple.getPhone());
        //client_os 放到扩展字段里面了
        extendsAttr.put("client_os", orderSimple.getClientOs());

        orderCustomerVO.setExtends_attr(JSON.toJSONString(extendsAttr));


        //会员采购订单 根据sku和区域获取定标商品
        List<String> skuList = new ArrayList<>();

        orderGoodsSimpleList.stream().forEach(e -> skuList.add(e.getSku().trim()));


        // 获取所有的组织
        List<OrganizationDto> organizationDtoList = OrgUtils.getOrgListByOrgId(sessionUser.getCurrentOrgID());

        Assert.isTrue(CollectionUtils.isNotEmpty(organizationDtoList), "获取用户组织下的组织集合为空");
        List<String> organizationIds = organizationDtoList.stream().map(OrganizationDto::getId).collect(Collectors.toList());

        String goodsPurchaseT = JdbcTemplateUtils.getTableName(ModelConst.T_GOODS_PURCHASE, AppConst.COMMODITYMATERIALS);
        String quotationGoodsT = JdbcTemplateUtils.getTableName(ModelConst.T_QUOTATION_GOODS, AppConst.SOURCING_CENTER);
        String inquiryGoodsT = JdbcTemplateUtils.getTableName(ModelConst.T_INQUIRY_GOODS, AppConst.SOURCING_CENTER);

        //inquiry_goods_id
        StringBuilder st = new StringBuilder(" SELECT purchase.*,quotation.num,inquiry.inquiry_id,purchase.quotation_goods_id FROM ");
        st.append(goodsPurchaseT);
        st.append(" purchase LEFT JOIN  ");
        st.append(quotationGoodsT);
        st.append(" quotation  ON  purchase.quotation_goods_id = quotation.id LEFT JOIN  ");
        st.append(inquiryGoodsT);
        st.append(" inquiry  ON  inquiry.id = quotation.inquiry_goods_id  ");
        st.append(" WHERE purchase.del = FALSE AND purchase.enabled = TRUE AND purchase.enabled = TRUE  ");
        st.append(" AND JSON_UNQUOTE(purchase.customer_id -> '$.id') IN ( :organizationIds ) AND  purchase.customer_sku IN ( :skuList ) AND inquiry.area = :area ");

        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("organizationIds", organizationIds);
        queryParam.put("skuList", skuList);
        queryParam.put("area", address.get("post"));

        List<Map<String, Object>> goodsPurchaseList = JdbcTemplateUtils.queryForList(st.toString(), queryParam);

        Assert.isTrue(CollectionUtils.isNotEmpty(goodsPurchaseList), "未获取到可下单的定标商品，请检查参数是否正确");

        List<OrderCustomerGoodsVO> orderCustomerGoodsVOList = new ArrayList<>();
        List<OrderVendorGoodsVO> orderVendorGoodsVOList = new ArrayList<>();
        for (OrderGoodsSimple orderGoodsSimple : orderGoodsSimpleList) {

            List<Map<String, Object>> filterGoodsPurchaseList = goodsPurchaseList.stream()
                    .filter(t -> t.get("customer_sku").equals(orderGoodsSimple.getSku()))
                    .collect(Collectors.toList());

            Assert.isTrue(filterGoodsPurchaseList.size() != 1, "公司【" + orderGoodsSimple.getCompany() + "】和客户料号【"
                    + orderGoodsSimple.getSku() + "】" + (filterGoodsPurchaseList.size() > 1 ? "锁定多条定标商品" : "未锁定到定标商品，请检查参数是否正确"));

            Map<String, Object> goodsPurchase = filterGoodsPurchaseList.get(0);
            GoodsSrcEnum type = GoodsSrcEnum.switchNew(goodsPurchase.get("type").equals(GoodsPurchaseTypeEnum.SINGLE) ? 2 : 3);

            OrderCustomerGoodsVO orderCustomerGoodsVO = new OrderCustomerGoodsVO();
            orderCustomerGoodsVO.setSku(orderGoodsSimple.getSku());
            //todo company
            orderCustomerGoodsVO.setGoods_src(type);
            orderCustomerGoodsVO.setGoods_id(String.valueOf(goodsPurchase.get("id")));
            orderCustomerGoodsVO.setQuantity(null != orderGoodsSimple.getQuantity() ? orderGoodsSimple.getQuantity() : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("num")));
            orderCustomerGoodsVO.setClient_order_goods_id(UUID.randomUUID().toString());
            orderCustomerGoodsVO.setPrice(orderGoodsSimple.getPrice());
            orderCustomerGoodsVO.setAmount(orderGoodsSimple.getAmount());

            orderCustomerGoodsVO.setCompany(orderGoodsSimple.getCompany());
            orderCustomerGoodsVO.setWarehouse(orderGoodsSimple.getWarehouse());
            orderCustomerGoodsVO.setRegion(String.valueOf(address.get("post")));

            OrderVendorGoodsVO orderVendorGoodsVO = new OrderVendorGoodsVO();
            orderVendorGoodsVO.setSku(orderGoodsSimple.getSku());
            orderVendorGoodsVO.setGoods_src(type);
            orderVendorGoodsVO.setGoods_id(String.valueOf(goodsPurchase.get("id")));
            orderVendorGoodsVO.setQuantity(null != orderGoodsSimple.getQuantity() ? orderGoodsSimple.getQuantity() : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("num")));
            orderVendorGoodsVO.setClient_order_goods_id(UUID.randomUUID().toString());
            orderVendorGoodsVO.setPrice(orderGoodsSimple.getPrice());
            orderVendorGoodsVO.setAmount(orderGoodsSimple.getAmount());


            //todo orderCustomerGoodsVO.setWarehouse(orderGoodsSimple.getWarehouse());
            orderCustomerGoodsVOList.add(orderCustomerGoodsVO);
            orderVendorGoodsVOList.add(orderVendorGoodsVO);
        }

        orderCustomerVO.setOrderCustomerGoodsVOList(orderCustomerGoodsVOList);
        orderCustomerVO.setOrderVendorGoodsVOList(orderVendorGoodsVOList);
        return orderCustomerVO;
    }

    @Override
    public OrderCustomerVO builderCustomerOrder(OrderCustomerVO orderCustomerVO, SessionUser sessionUser) {

        Assert.isTrue(null != orderCustomerVO, "客户订单不能为空 ！");
        Assert.isTrue(CollectionUtils.isNotEmpty(orderCustomerVO.getOrderCustomerGoodsVOList()), "客户商品信息不存在！");
        Assert.isTrue(CollectionUtils.isNotEmpty(orderCustomerVO.getOrderVendorGoodsVOList()), "供应商商品信息不存在！");

        List<OrderVendorVO> vendorOrders = new ArrayList<>();
        Map<String, OrderVendorGoodsVO> orderVendorGoodsVOMap = orderCustomerVO.getOrderVendorGoodsVOList().stream().collect(Collectors.toMap(OrderVendorGoodsVO::getErp_po, e -> e));
        for (OrderCustomerGoodsVO orderCustomerGoodsVO : orderCustomerVO.getOrderCustomerGoodsVOList()) {
            OrderVendorGoodsVO orderVendorGoodsVO = orderVendorGoodsVOMap.get(orderCustomerGoodsVO.getErp_po());
            //判断外部来源订单Id是否已存在
            List<Map<String, Object>> allByClientOrderId = findAllByClientOrderId(orderCustomerGoodsVO.getClient_order_goods_id(), sessionUser.getCurrentUserId());

            Assert.isTrue(CollectionUtils.isEmpty(allByClientOrderId) || "gomro_api".equals(sessionUser.getCurrentClientID())
                            || "gomro_ios".equals(sessionUser.getCurrentClientID()),
                    "来源订单商品id：【" + orderCustomerGoodsVO.getClient_order_goods_id() + "】已存在,请更换!");

            SelectorFormat vendorId = null;
            if (GoodsSrcEnum.Shop == orderCustomerGoodsVO.getGoods_src() || GoodsSrcEnum.SourcingSingle == orderCustomerGoodsVO.getGoods_src()) {

                Map<String, Object> goodsPurchase = JdbcTemplateUtils.builder(AppConst.COMMODITYMATERIALS, ModelConst.T_GOODS_PURCHASE).selectField("*")
                        .eq("id", orderCustomerGoodsVO.getGoods_id()).queryForMap();


                Assert.isTrue(null != goodsPurchase, "来源商品：" + orderCustomerGoodsVO.getClient_order_goods_id() + "不存在!");

                Assert.isTrue(Boolean.valueOf(String.valueOf(goodsPurchase.get("enabled"))), "来源商品：" + orderCustomerGoodsVO.getClient_order_goods_id() + "已不可采购，请重新询价！");

                List<SelectorFormat> vendorSelectorFormats = JsonParseObject.parseObject(String.valueOf(goodsPurchase.get("vendor_id")), SelectorFormat.class);
                Assert.isTrue(null != vendorSelectorFormats, "供应商信息为空");

                vendorId = vendorSelectorFormats.get(0);

                // 增加友好返回
                // GoodsPurchaseTypeEnum.SINGLE(1, "单次"), // 询价单次采购
                // GoodsPurchaseTypeEnum.LOOP(2, "循环"); // 询价循环采购
                // 商品来源类型 1 固买商城，2 寻源商品, 3 企业商城, 4 外部商城订单
                // 这应该是入参逻辑错误，实际应用中，应该封装内容，只暴露必要的参数
                // src 属性是系统产生，不需要参数也不需要“暗号验证”
                Assert.isTrue(GoodsSrcEnum.Shop == orderCustomerGoodsVO.getGoods_src() ||
                                !GoodsPurchaseTypeEnum.SINGLE.equals(goodsPurchase.get("type")),
                        "参数 src 非寻源商品(" + orderCustomerGoodsVO.getGoods_src() + ")，采购类型不能为单次采购(" + goodsPurchase.get("type") + ")，订单商品(name:" + orderCustomerGoodsVO.getName() + ",id:" + orderCustomerGoodsVO.getClient_order_goods_id() + ") 请检查!");

                Assert.isTrue(GoodsSrcEnum.SourcingSingle == orderCustomerGoodsVO.getGoods_src() ||
                                !GoodsPurchaseTypeEnum.LOOP.equals(goodsPurchase.get("type")),
                        "参数 src 非企业商城(" + orderCustomerGoodsVO.getGoods_src() + ")，采购类型不能为循环采购(" + goodsPurchase.get("type") + ")，订单商品(name:" + orderCustomerGoodsVO.getName() + ",id:" + orderCustomerGoodsVO.getClient_order_goods_id() + ") 请检查!");

                Assert.isTrue(orderCustomerGoodsVO.getQuantity().compareTo(BigDecimal.ZERO) != -1 && !GoodsSrcEnum.Shop.equals(orderCustomerGoodsVO.getGoods_src()) &&
                                orderCustomerGoodsVO.getQuantity().subtract(BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("num"))).abs().compareTo(difference) == 1,
                        "原报价商品" + orderCustomerGoodsVO.getGoods_id() + "数量为" + goodsPurchase.get("num") + "，提交的订单商品数量为" + orderCustomerGoodsVO.getQuantity() + " 数量不对应，请检查。");

                //年度采购，判断采购数量
                if (GoodsSrcEnum.SourcingSingle == orderCustomerGoodsVO.getGoods_src()) {

                    boolean enabledAttribute = OrgAttributeUtils.isEnabledAttribute(sessionUser.getCurrentOrgID(), OrganizationAttributeEnum.STRATEGY_MORE);

                    //组织首次采购量大于等于询价量
                    Assert.isTrue(!enabledAttribute || orderCustomerGoodsVO.getQuantity().compareTo(BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("num"))) < 0,
                            "订单商品：" + orderCustomerGoodsVO.getClient_order_goods_id() + "的采购数量需要大于等于起订量" + goodsPurchase.get("num") + "!");
                }

                //todo 税率部分省略了

                //数据为null则不验证，直接取平台数据，否则验证小数点后2位误差
                if (null != orderCustomerGoodsVO.getPrice()) {

                    BigDecimal abs = orderCustomerGoodsVO.getPrice().subtract(BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("price"))).abs();
                    // 这是个高手 1e-6 就是 0.000001 也就是 1 * 10^-6
                    // 这个要表达的意思 应该是 入参的价格与系统价格的误差不能大小这个数
                    Assert.isTrue(abs.compareTo(difference) < 1,
                            "原报价商品" + orderCustomerGoodsVO.getGoods_id() + "价格：" + BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("price")) + "元，提交的订单商品价格：" + orderCustomerGoodsVO.getPrice() + "元 金额不对应，请检查。");

                }

                //客户订单商品
                orderCustomerGoodsVO.setCategory(String.valueOf(goodsPurchase.get("catalog")));
                orderCustomerGoodsVO.setBrand(String.valueOf(goodsPurchase.get("brand")));
                orderCustomerGoodsVO.setName(String.valueOf(goodsPurchase.get("name")));
                orderCustomerGoodsVO.setModel(String.valueOf(goodsPurchase.get("model")));
                orderCustomerGoodsVO.setSpec(String.valueOf(goodsPurchase.get("spec")));
                orderCustomerGoodsVO.setSku(null == goodsPurchase.get("customer_sku") ? "" : String.valueOf(goodsPurchase.get("customer_sku")));
                orderCustomerGoodsVO.setGolden_tax(null == goodsPurchase.get("golden_tax") ? "" : String.valueOf(goodsPurchase.get("golden_tax")));
                orderCustomerGoodsVO.setUnspsc(null == goodsPurchase.get("unspsc") ? "" : String.valueOf(goodsPurchase.get("unspsc")));
                orderCustomerGoodsVO.setImages(null == goodsPurchase.get("images") ? "" : String.valueOf(goodsPurchase.get("images")));
                orderCustomerGoodsVO.setDescription(null == goodsPurchase.get("description") ? "" : String.valueOf(goodsPurchase.get("description")));

                orderCustomerGoodsVO.setUnit(String.valueOf(goodsPurchase.get("unit")));
                orderCustomerGoodsVO.setPackage_unit(String.valueOf(goodsPurchase.get("package_unit")));
                orderCustomerGoodsVO.setPackage_quantity(null == goodsPurchase.get("package_num") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("package_num")));
                orderCustomerGoodsVO.setDelivery(null == goodsPurchase.get("delivery") ? null : BigDecimalUtils.bigDecimalToInteger(goodsPurchase.get("delivery")));
                //orderCustomerGoodsVO.setGoods_id(purchaseId.longValue());

                orderCustomerGoodsVO.setFreight_rate(null == goodsPurchase.get("tax_rate_freight") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("tax_rate_freight")));
                orderCustomerGoodsVO.setPretax_freight(null == goodsPurchase.get("pretax_freight") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("pretax_freight")));
                orderCustomerGoodsVO.setTax_rate(null == goodsPurchase.get("tax_rate") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("tax_rate")));
                orderCustomerGoodsVO.setPretax_price(null == goodsPurchase.get("pretax_price") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("pretax_price")));

                //供应商订单商品
                orderVendorGoodsVO.setCategory(String.valueOf(goodsPurchase.get("catalog")));
                orderVendorGoodsVO.setBrand(String.valueOf(goodsPurchase.get("brand")));
                orderVendorGoodsVO.setName(String.valueOf(goodsPurchase.get("name")));
                orderVendorGoodsVO.setModel(String.valueOf(goodsPurchase.get("model")));
                orderVendorGoodsVO.setSpec(String.valueOf(goodsPurchase.get("spec")));
                orderVendorGoodsVO.setSku(null == goodsPurchase.get("customer_sku") ? "" : String.valueOf(goodsPurchase.get("customer_sku")));
                orderVendorGoodsVO.setGolden_tax(null == goodsPurchase.get("golden_tax") ? "" : String.valueOf(goodsPurchase.get("golden_tax")));
                orderVendorGoodsVO.setUnspsc(null == goodsPurchase.get("unspsc") ? "" : String.valueOf(goodsPurchase.get("unspsc")));
                orderVendorGoodsVO.setImages(null == goodsPurchase.get("images") ? "" : String.valueOf(goodsPurchase.get("images")));
                orderVendorGoodsVO.setDescription(null == goodsPurchase.get("description") ? "" : String.valueOf(goodsPurchase.get("description")));

                orderVendorGoodsVO.setUnit(String.valueOf(goodsPurchase.get("unit")));
                orderVendorGoodsVO.setPackage_unit(String.valueOf(goodsPurchase.get("package_unit")));
                orderVendorGoodsVO.setPackage_quantity(null == goodsPurchase.get("package_num") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("package_num")));
                orderVendorGoodsVO.setDelivery(null == goodsPurchase.get("delivery") ? null : BigDecimalUtils.bigDecimalToInteger(goodsPurchase.get("delivery")));
                //orderCustomerGoodsVO.setGoods_id(purchaseId.longValue());

                orderVendorGoodsVO.setFreight_rate(null == goodsPurchase.get("tax_rate_freight") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("tax_rate_freight")));
                orderVendorGoodsVO.setPretax_freight(null == goodsPurchase.get("pretax_freight") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("pretax_freight")));
                orderVendorGoodsVO.setTax_rate(null == goodsPurchase.get("tax_rate") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("tax_rate")));
                orderVendorGoodsVO.setPretax_price(null == goodsPurchase.get("pretax_price") ? null : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("pretax_price")));


                //todo 订单商品关系表数据
                //外部来源订单记录询价信息
                try {
                    //订单商品关系表数据
                    Map<String, Object> OrderGoodsRelation = new HashMap<>();

                    //获取询价单数据
                    Map<String, Object> inquiry = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_INQUIRY).selectField("*").eq("id", goodsPurchase.get("inquiry_id")).queryForMap();

                    OrderGoodsRelation.put("warehouse", orderCustomerGoodsVO.getWarehouse());
                    OrderGoodsRelation.put("company", orderCustomerGoodsVO.getCompany());
                    OrderGoodsRelation.put("region", orderCustomerGoodsVO.getRegion());
                    OrderGoodsRelation.put("inquiry_id", inquiry.get("id"));
                    OrderGoodsRelation.put("inquiry_member_id", inquiry.get("member_id"));
                    OrderGoodsRelation.put("demand_department_name", inquiry.get("target_department_name"));

                    //创建订单商品关系表
                    SingleResponse<BO> bo = BoServiceUtils.createBo(ModelConst.T_ORDER_GOODS_RELATION, Collections.singletonList(OrderGoodsRelation));
                    Assert.isTrue(!bo.isSuccess(), "保存商品关系表数据失败！");
                    orderCustomerGoodsVO.setRelation_id(String.valueOf(bo.getData().getBizObjectId()));
                    orderVendorGoodsVO.setRelation_id(String.valueOf(bo.getData().getBizObjectId()));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            //todo 商品对应的代码
//            if (RegexUtils.notNull(order.getClientFactoryCode())) {
//                orderGoods.setExtendsAttr(OrderGoodsExtendsAttrVO.writeValueAsString(OrderGoodsExtendsAttrVO.builder().clientFactoryCode(order.getClientFactoryCode()).build()));
//            }

            boolean existVendor = false;
            for (OrderVendorVO vendorOrder : vendorOrders) {
                if (vendorId.getId().equals(vendorOrder.getOrganization_id().getId())) {

                    if (null == vendorOrder.getOrderCustomerGoodsVOList())
                        vendorOrder.setOrderVendorGoodsVOList(new ArrayList<>());
                    if (null == vendorOrder.getOrderVendorGoodsVOList())
                        vendorOrder.setOrderVendorGoodsVOList(new ArrayList<>());

                    for (OrderCustomerGoodsVO og : vendorOrder.getOrderCustomerGoodsVOList()) {
                        Assert.isTrue(!og.getGoods_src().equals(orderCustomerGoodsVO.getGoods_src()) ||
                                !og.getGoods_id().equals(orderCustomerGoodsVO.getGoods_id()), "存在重复商品!");

                    }
                    orderCustomerGoodsVO.setOrderVendorVO(vendorOrder);
                    vendorOrder.getOrderCustomerGoodsVOList().add(orderCustomerGoodsVO);
                    vendorOrder.getOrderVendorGoodsVOList().add(orderVendorGoodsVO);
                    existVendor = true;
                    break;
                }
            }

            if (!existVendor) {

                OrderVendorVO orderVendorVO = new OrderVendorVO();
                orderVendorVO.setOrganization_id(vendorId);
                orderVendorVO.setPlace_order_time(new Date());
                orderVendorVO.setMemo(null == orderCustomerGoodsVO.getMemo() ? "" : orderCustomerGoodsVO.getMemo());

                orderVendorVO.setOrderCustomerGoodsVOList(new ArrayList<>());
                orderCustomerGoodsVO.setOrderVendorVO(orderVendorVO);
                orderVendorVO.getOrderCustomerGoodsVOList().add(orderCustomerGoodsVO);
                orderVendorVO.setOrderCustomerVO(orderCustomerVO);
                vendorOrders.add(orderVendorVO);

            }

        }

        //建客户订单
        orderCustomerVO.setType(OrderTypeEnum.ClientOrder);
        orderCustomerVO.setOrderVendorVOList(vendorOrders);
        orderCustomerVO.setClient_id(sessionUser.getCurrentClientID());
        orderCustomerVO.setPlace_order_user_id(sessionUser.getUserFormat());
        orderCustomerVO.setPayment_method(PaymentMethodEnum.Credit);

        return orderCustomerVO;
    }

    @Override
    public OrderCustomerVO createSimpleCustomerOrder(OrderCustomerVO orderCustomerVOBuild, SessionUser sessionUser) {

        OrganizationDto organizationDto = OrgUtils.getOrgByOrgId(sessionUser.getCurrentOrgID());

        Assert.isTrue(null != organizationDto, "用户组织不可用!");

        boolean overdue = OrgAttributeUtils.isEnabledAttribute(sessionUser.getCurrentOrgID(), OrganizationAttributeEnum.OVERDUE_BUT_NOT_INVOICED);
        if (overdue) {

            List<OrganizationDto> organizationDtoList = OrgUtils.getOrgListByOrgId(sessionUser.getCurrentOrgID());

            Assert.isTrue(CollectionUtils.isNotEmpty(organizationDtoList), "获取的ID列表为空!");

            List<String> organizationIds = organizationDtoList.stream().map(e -> e.getId()).collect(Collectors.toList());
            //t_bill TradeDirection
            //todo TradeDirection
            List<Map<String, Object>> billList = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_BILL).selectField("*")
                    .in("organization_id -> &id", organizationIds).eq("direction", "Sale").queryForList();

            Assert.isTrue(CollectionUtils.isNotEmpty(billList), "获取账单列表为空!");

            //t_trade
            List<String> tradeIdList = billList.stream().map(e -> String.valueOf(e.get("trade_id"))).collect(Collectors.toList());
            List<Map<String, Object>> tradeList = JdbcTemplateUtils.builder(AppConst.FINANCIALCENTER, ModelConst.T_TRADE).selectField("*").in("id", tradeIdList).queryForList();

            Date now = new Date();
            Date delivery = null;
            for (Map<String, Object> bill : billList) {
                Date billDate = Utils.strToDate(String.valueOf(bill.get("bill_date")));
                Instant instant = billDate.toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                delivery = Date.from(instant.atZone(zoneId).toLocalDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
                int day = (int) ((now.getTime() - delivery.getTime()) / (1000 * 3600 * 24));
                Assert.isTrue(day <= 30, "部分商品已收货超30天，仍未申请开票,请前往申票，否则无法创建订单！");
            }
        }


        OrganizationDto tranOrg = organizationDto;
        if (!organizationDto.getId().equals(organizationDto.getTransaction_organization_id().get(0).getId())) {
            OrganizationDto organizationTransactionDto = OrgUtils.getOrgByOrgId(organizationDto.getTransaction_organization_id().get(0).getId());

            Assert.isTrue(null != organizationTransactionDto, "未获取到对应的结算组织！");

            tranOrg = organizationTransactionDto;
        }

        Assert.isTrue(null != tranOrg.getAccount_id(), "结算组织账户不能为空，请联系管理员添加结算组织账户！");

        //客户账期
        Assert.isTrue(null != tranOrg.getStatement_cycle() && tranOrg.getStatement_cycle() > 0, "请联系平台管理员添加客户账期！");
        Integer cap = tranOrg.getStatement_cycle();

        //校验参数
        checkOrder(orderCustomerVOBuild);

        //设置客户订单属性->客户下单客户订单状态为待付款
        //todo label 待付款 =》未付款 & label!=审批中
        orderCustomerVOBuild.setOrder_customer_status(OrderCustomerStatusEnum.UpcomingPayment);

        //customerOrder.setAccountPeriod(cap);

        //source
        if (null == orderCustomerVOBuild.getType()) {
            orderCustomerVOBuild.setType(OrderTypeEnum.PurchaseOrder);
        }

        // List<Long> vendorIds = iOrganizationInviteCodeService.listVendorByCustomerId(orgId);
        List<String> vendorIds = new ArrayList<>();

        for (OrderVendorVO orderVendorVO : orderCustomerVOBuild.getOrderVendorVOList()) {

            //客户下单 ->供应商订单状态为新建  新建 =》未付款
            orderVendorVO.setOrder_vendor_status(OrderVendorStatusEnum.UpcomingPayment);

            // 获取供应商账期
            OrganizationDto vendorOrg = OrgUtils.getOrgByOrgId(orderVendorVO.getOrganization_id().getId());

            Assert.isTrue(CollectionUtils.isNotEmpty(vendorOrg.getTransaction_organization_id()), "请联系平台管理员添加供应商结算组织!(1)");

            OrganizationDto accountOrganization = OrgUtils.getOrgByOrgId(vendorOrg.getTransaction_organization_id().get(0).getId());

            Assert.isTrue(null != accountOrganization, "请联系平台管理员添加供应商结算组织!(2)");

            Assert.isTrue(null != accountOrganization.getStatement_cycle(), "请联系平台管理员添加供应商结算账期！");

            Integer vap = accountOrganization.getStatement_cycle();

            orderVendorVO.setOrganization_name(vendorOrg.getName());
            //vendorOrder.setAccountPeriod(vap);

            // 这里是结算信息状态 是否还需要？ 确认去掉了
            //vendorOrder.setReconciliationStatus(ReconciliationStatusEnum.UNDO);
            //vendorOrder.setInvoiceStatus(InvoiceStatusEnum.UNDO);
            // vendorOrder.setPaymentStatus(PaymentStatusEnum.UNDO);

            orderVendorVO.setOrderCustomerVO(orderCustomerVOBuild);

            // 邀请供应商为空或者不包含当前供应商则为平台供应商 todo 新的模型 organization_type 供应商组织类型
            //vendorOrder.setPlatform(!CollectionUtils.isEmpty(vendorIds) && vendorIds.contains(vendorOrder.getVendorId()));
            orderVendorVO.setOrganization_type(!CollectionUtils.isEmpty(vendorIds) && vendorIds.contains(orderVendorVO.getOrganization_id()));

            // 校验订单商品 orderGoods
            Assert.isTrue(CollectionUtils.isNotEmpty(orderVendorVO.getOrderCustomerGoodsVOList()), "供应商订单商品错误！");
            Assert.isTrue(CollectionUtils.isNotEmpty(orderVendorVO.getOrderVendorGoodsVOList()), "供应商订单商品错误！");

            Map<String, OrderVendorGoodsVO> orderVendorGoodsVOMap = orderVendorVO.getOrderVendorGoodsVOList().stream().collect(Collectors.toMap(OrderVendorGoodsVO::getErp_po, e -> e));

            //循环设置订单商品信息
            for (OrderCustomerGoodsVO orderCustomerGoodsVO : orderVendorVO.getOrderCustomerGoodsVOList()) {
                Assert.isTrue(orderCustomerGoodsVO.getQuantity().compareTo(BigDecimal.ZERO) <= 0, "订单商品数量错误! ");

                OrderVendorGoodsVO orderVendorGoodsVO = orderVendorGoodsVOMap.get(orderCustomerGoodsVO.getErp_po());

                boolean isPurchase = orderCustomerGoodsVO.getGoods_src() == GoodsSrcEnum.SourcingSingle || orderCustomerGoodsVO.getGoods_src() == GoodsSrcEnum.SourcingLoop;

                orderCustomerGoodsVO.setVendor_account_period(vap);
                orderCustomerGoodsVO.setCustomer_account_period(cap);
                orderCustomerGoodsVO.setReturned_num(BigDecimal.ZERO);
                orderCustomerGoodsVO.setReturn_received_num(BigDecimal.ZERO);

                orderVendorGoodsVO.setVendor_account_period(vap);
                orderVendorGoodsVO.setCustomer_account_period(cap);
                orderVendorGoodsVO.setReturned_num(BigDecimal.ZERO);
                orderVendorGoodsVO.setReturn_received_num(BigDecimal.ZERO);


                //客户下单 ->订单商品状态为待付款
                // todo 待付款 =》未付款 & label!=审批中
                //orderGoods.put("order_vendor_goods_status", OrderGoodsStatusEnum.UpcomingPayment);
                //orderGoods.setCustomerAccountPeriod(cap);
                //orderGoods.setVendorAccountPeriod(vap);

                if (null == orderCustomerGoodsVO.getTechnical()) orderCustomerGoodsVO.setTechnical("");
                if (null == orderCustomerGoodsVO.getPackaging()) orderCustomerGoodsVO.setPackaging("");
                if (null == orderCustomerGoodsVO.getMemo()) orderCustomerGoodsVO.setMemo("");
                if (null == orderCustomerGoodsVO.getWarranty()) orderCustomerGoodsVO.setWarranty("");
                if (null == orderCustomerGoodsVO.getBar_code()) orderCustomerGoodsVO.setBar_code("");
                if (null == orderCustomerGoodsVO.getAttachment()) orderCustomerGoodsVO.setAttachment("");
                if (null == orderCustomerGoodsVO.getGolden_tax()) orderCustomerGoodsVO.setGolden_tax("");
                if (null == orderCustomerGoodsVO.getUnspsc()) orderCustomerGoodsVO.setUnspsc("");
                if (null == orderCustomerGoodsVO.getDelivery()) orderCustomerGoodsVO.setDelivery(0);

                if (null == orderVendorGoodsVO.getTechnical()) orderVendorGoodsVO.setTechnical("");
                if (null == orderVendorGoodsVO.getPackaging()) orderVendorGoodsVO.setPackaging("");
                if (null == orderVendorGoodsVO.getMemo()) orderVendorGoodsVO.setMemo("");
                if (null == orderVendorGoodsVO.getWarranty()) orderVendorGoodsVO.setWarranty("");
                if (null == orderVendorGoodsVO.getBar_code()) orderVendorGoodsVO.setBar_code("");
                if (null == orderVendorGoodsVO.getAttachment()) orderVendorGoodsVO.setAttachment("");
                if (null == orderVendorGoodsVO.getGolden_tax()) orderVendorGoodsVO.setGolden_tax("");
                if (null == orderVendorGoodsVO.getUnspsc()) orderVendorGoodsVO.setUnspsc("");
                if (null == orderVendorGoodsVO.getDelivery()) orderVendorGoodsVO.setDelivery(0);


                if (orderCustomerGoodsVO.getGoods_src().equals(GoodsSrcEnum.Shop)) {
                    //todo 需要扣减库存


                }


                //根据业务数据分析逻辑这里省略了部分无效逻辑代码
                if (isPurchase) {
                    //根据 组织采购表id 查询组织采购数据
                    Map<String, Object> goodsPurchase = JdbcTemplateUtils.builder(AppConst.COMMODITYMATERIALS, ModelConst.T_GOODS_PURCHASE).selectField("*").eq("id", orderCustomerGoodsVO.getGoods_id()).queryForMap();

                    Assert.isTrue(null != goodsPurchase, "订单商品不存在！");

                    Date expire = Utils.strToDate(String.valueOf(goodsPurchase.get("expire")));

                    Assert.isTrue(expire.getTime() >= System.currentTimeMillis(), "商品已过期，请重新询价！");


                    Map<String, Object> quotationGoodsEntity;
                    //循环采购不限制采购权限
                    if (orderCustomerGoodsVO.getGoods_src() == GoodsSrcEnum.SourcingSingle) {

                        //需要校验权限

                        List<String> memberIds = UserUtils.listSubMemberIds(sessionUser.getCurrentUserId());

                        String inquiryT = JdbcTemplateUtils.getTableName(ModelConst.T_INQUIRY, AppConst.SOURCING_CENTER);
                        String quotationGoodsT = JdbcTemplateUtils.getTableName(ModelConst.T_QUOTATION_GOODS, AppConst.SOURCING_CENTER);
                        String inquiryGoodsT = JdbcTemplateUtils.getTableName(ModelConst.T_INQUIRY_GOODS, AppConst.SOURCING_CENTER);

                        //inquiry_goods_id
                        StringBuilder st = new StringBuilder(" SELECT q.* FROM ");
                        st.append(quotationGoodsT);
                        st.append(" q LEFT JOIN  ");
                        st.append(inquiryGoodsT);
                        st.append(" ig  ON  q.inquiry_goods_id = ig.id LEFT JOIN  ");
                        st.append(inquiryT);
                        st.append(" i  ON  i.id = ig.inquiry_id  ");
                        st.append(" WHERE q.id = :quotationGoodsId  ");

                        Map<String, Object> queryParam = new HashMap<>();
                        queryParam.put("quotationGoodsId", goodsPurchase.get("quotation_goods_id"));

                        if (CollectionUtils.isNotEmpty(memberIds)) {
                            st.append(" AND JSON_UNQUOTE(i.member_id -> '$.id') IN ( :memberIds ) ");
                            queryParam.put("memberIds", memberIds);
                        }

                        List<Map<String, Object>> goodsPurchaseList = JdbcTemplateUtils.queryForList(st.toString(), queryParam);

//                    if (null != memberIds && !memberIds.contains(memberId)) {
//                        log.error("{} {} {} {} ", "getQuotationGoods()", "超出权限查看", "操作人能操作的用户ids:"
//                                + memberIds + " 所操作的商品所属的用户ids:" + memberId, sessionUser.getCurrentUserID());
//                        throw new InquiryException("查看报价商品失败：询价商品不在可操作权限内");
//                    }
                        Assert.isTrue(CollectionUtils.isNotEmpty(goodsPurchaseList), "查看报价商品失败：询价商品不在可操作权限内！or 询价商品没数据！");

                        quotationGoodsEntity = goodsPurchaseList.get(0);
                    } else {
                        //不需要校验权限
                        quotationGoodsEntity = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_QUOTATION_GOODS).selectField("*").eq("id", goodsPurchase.get("quotation_goods_id")).queryForMap();
                    }

                    Assert.isTrue(null != quotationGoodsEntity, "未获取到报价商品，暂无采购权限!");

                    //询价单
                    Map<String, Object> inquiryGoodsEntity = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_INQUIRY_GOODS).selectField("*").eq("id", quotationGoodsEntity.get("inquiry_goods_id")).queryForMap();
                    Assert.isTrue(null != inquiryGoodsEntity, "未获取到询价单!");

                    Map<String, Object> inquiryEntity = JdbcTemplateUtils.builder(AppConst.SOURCING_CENTER, ModelConst.T_INQUIRY).selectField("*").eq("id", inquiryGoodsEntity.get("inquiry_id")).queryForMap();
                    Assert.isTrue(null != inquiryEntity, "未获取到询价单!");

                    //采购商品账期取询价单的账期
                    orderCustomerGoodsVO.setCustomer_account_period(BigDecimalUtils.bigDecimalToInteger(inquiryGoodsEntity.get("account_period")));
                    orderCustomerGoodsVO.setClient_order_vendor_goods_id(String.valueOf(quotationGoodsEntity.get("client_vendor_goods_id")));

                    orderVendorGoodsVO.setCustomer_account_period(BigDecimalUtils.bigDecimalToInteger(inquiryGoodsEntity.get("account_period")));
                    orderVendorGoodsVO.setClient_order_vendor_goods_id(String.valueOf(quotationGoodsEntity.get("client_vendor_goods_id")));

                    orderVendorVO.getOrderVendorGoodsVOList().add(orderVendorGoodsVO);

                }
            }
        }
        //如果erpPo没值，把 clientOs 赋给它
        if (!RegexUtils.notNull(orderCustomerVOBuild.getErp_po())) {
            orderCustomerVOBuild.setErp_po(Objects.toString(orderCustomerVOBuild.getClient_order_id(), ""));
        }

        // 保存客户订单 & 客户订单商品 & 保存供应商订单 & 供应商订单商品
        Map<String, Object> customerMap = OrderCustomerVO.transferMap(orderCustomerVOBuild);
        SingleResponse<BO> customerOrderBo = BoServiceUtils.createBo(ModelConst.T_ORDER_CUSTOMER, Collections.singletonList(customerMap));
        Assert.isTrue(!customerOrderBo.isSuccess(), "客户订单创建失败！");
        String customerOrderId = customerOrderBo.getData().getBizObjectId();
        orderCustomerVOBuild.setId(customerOrderId);

        List<String> vendorOrderIds = new ArrayList<>();
        for (OrderVendorVO orderVendorVO : orderCustomerVOBuild.getOrderVendorVOList()) {

            Map<String, Object> vendorMap = OrderVendorVO.transferMap(orderVendorVO);
            vendorMap.put("order_customer_id", customerOrderId);
            SingleResponse<BO> vendorOrderBo = BoServiceUtils.createBo(ModelConst.T_ORDER_VENDOR, Collections.singletonList(vendorMap));
            Assert.isTrue(!vendorOrderBo.isSuccess(), "供应商订单创建失败！");
            String vendorOrderId = vendorOrderBo.getData().getBizObjectId();


            List<Map<String, Object>> customerGoodsMapList = new ArrayList<>();
            List<Map<String, Object>> vendorGoodsMapList = new ArrayList<>();
            for (OrderCustomerGoodsVO orderCustomerGoodsVO : orderVendorVO.getOrderCustomerGoodsVOList()) {
                Map<String, Object> customerGoodsMap = OrderCustomerGoodsVO.transferMap(orderCustomerGoodsVO);
                customerGoodsMap.put("order_customer_id", orderCustomerVOBuild.getId());
                customerGoodsMap.put("order_vendor_id", vendorOrderId);
                customerGoodsMapList.add(customerGoodsMap);
            }

            for (OrderVendorGoodsVO orderVendorGoodsVO : orderVendorVO.getOrderVendorGoodsVOList()) {
                Map<String, Object> vendorGoodsMap = OrderVendorGoodsVO.transferMap(orderVendorGoodsVO);
                vendorGoodsMap.put("order_customer_id", customerOrderId);
                vendorGoodsMap.put("order_vendor_id", vendorOrderId);
                vendorGoodsMapList.add(vendorGoodsMap);
            }

            SingleResponse<BO> customerOrderGoodsBo = BoServiceUtils.createBo(ModelConst.T_ORDER_CUSTOMER_GOODS, customerGoodsMapList);
            Assert.isTrue(!customerOrderGoodsBo.isSuccess(), "客户订单商品创建失败！");

            SingleResponse<BO> vendorOrderGoodsBo = BoServiceUtils.createBo(ModelConst.T_ORDER_VENDOR_GOODS, vendorGoodsMapList);
            Assert.isTrue(!vendorOrderGoodsBo.isSuccess(), "供应商订单商品创建失败！");

            vendorOrderIds.add(vendorOrderId);
        }

        //todo 根据供应商订单 判断是否有虚拟供应商，是否需要创建转采订单


        return orderCustomerVOBuild;
    }

    @Override
    public CustomerOrderVo adaptationSaveSimple(OrderSimple orderSimple, SessionUser sessionUser) {
        CustomerOrderVo customerOrderVo = new CustomerOrderVo();
        //获取牧原区域对照表中的固买收货信息
        Map<String, Object> address = this.getDeliverAddressByCompany(sessionUser.getCurrentUserId(), orderSimple.getOrderGoodsList().stream().map(OrderGoodsSimple::getCompany).collect(Collectors.toSet()));
        customerOrderVo.setAddress(String.valueOf(address.get("address")));
        customerOrderVo.setReceiver(String.valueOf(address.get("receiver_name")));
        customerOrderVo.setPhone(String.valueOf(address.get("mobile")));
        customerOrderVo.setClient_order_id(orderSimple.getClientOrderId());
        customerOrderVo.setClient_user_id(orderSimple.getClientUserId());
        customerOrderVo.setActual_order(orderSimple.getActualOrder());
        customerOrderVo.setClient_os(orderSimple.getClientOs());
        customerOrderVo.setErp_po(orderSimple.getErpPO());

        //牧原下单需要把实际收货人setup给实际下单人
        if ("mysp_api".equals(sessionUser.getCurrentClientID())) {
            //orderVo.setActualOrder(param.getReceiver());
            customerOrderVo.setActual_order(orderSimple.getReceiver());
        }

        String extendsAttr = OrderCustomerExtendsAttr.conversion(OrderCustomerExtendsAttr.builder()
                        .address(orderSimple.getAddress())
                        .receiver(orderSimple.getReceiver())
                        .phone(orderSimple.getPhone())
                        .build()
                , true);
        customerOrderVo.setExtends_attr(extendsAttr);

        Assert.isTrue(RegexUtils.notNull(String.valueOf(address.get("post"))), "区域不能为空");

        //会员采购订单 根据sku和区域获取定标商品
        List<String> skuList = new ArrayList<>();

        orderSimple.getOrderGoodsList().stream().forEach(e -> skuList.add(e.getSku().trim()));
        // 获取所有的组织
        List<OrganizationDto> organizationDtoList = OrgUtils.getOrgListByOrgId(sessionUser.getCurrentOrgID());

        Assert.isTrue(CollectionUtils.isNotEmpty(organizationDtoList), "获取用户组织下的组织集合为空");
        List<String> organizationIds = organizationDtoList.stream().map(OrganizationDto::getId).collect(Collectors.toList());

        String goodsPurchaseT = JdbcTemplateUtils.getTableName(ModelConst.T_GOODS_PURCHASE, AppConst.COMMODITYMATERIALS);
        String quotationGoodsT = JdbcTemplateUtils.getTableName(ModelConst.T_QUOTATION_GOODS, AppConst.SOURCING_CENTER);
        String inquiryGoodsT = JdbcTemplateUtils.getTableName(ModelConst.T_INQUIRY_GOODS, AppConst.SOURCING_CENTER);

        //inquiry_goods_id
        StringBuilder st = new StringBuilder(" SELECT purchase.*,quotation.num,inquiry.inquiry_id,purchase.quotation_goods_id FROM ");
        st.append(goodsPurchaseT);
        st.append(" purchase LEFT JOIN  ");
        st.append(quotationGoodsT);
        st.append(" quotation  ON  purchase.quotation_goods_id = quotation.id LEFT JOIN  ");
        st.append(inquiryGoodsT);
        st.append(" inquiry  ON  inquiry.id = quotation.inquiry_goods_id  ");
        st.append(" WHERE purchase.del = FALSE AND purchase.enabled = TRUE AND purchase.enabled = TRUE  ");
        st.append(" AND JSON_UNQUOTE(purchase.customer_id -> '$.id') IN ( :organizationIds ) AND  purchase.customer_sku IN ( :skuList ) AND inquiry.area = :area ");

        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("organizationIds", organizationIds);
        queryParam.put("skuList", skuList);
        queryParam.put("area", address.get("post"));

        log.info("sql:{}", st);
        log.info("queryParam:{}", queryParam);

        List<Map<String, Object>> goodsPurchaseList = JdbcTemplateUtils.queryForList(st.toString(), queryParam);

        Assert.isTrue(CollectionUtils.isNotEmpty(goodsPurchaseList), "未获取到可下单的定标商品，请检查参数是否正确");

        List<CustomerOrderGoodsVo> orderCustomerGoodsVOList = new ArrayList<>();
        for (OrderGoodsSimple orderGoodsSimple : orderSimple.getOrderGoodsList()) {

            List<Map<String, Object>> filterGoodsPurchaseList = goodsPurchaseList.stream()
                    .filter(t -> t.get("customer_sku").equals(orderGoodsSimple.getSku()))
                    .collect(Collectors.toList());

            Assert.isTrue(filterGoodsPurchaseList.size() == 1, "公司【" + orderGoodsSimple.getCompany() + "】和客户料号【"
                    + orderGoodsSimple.getSku() + "】" + (filterGoodsPurchaseList.size() > 1 ? "锁定多条定标商品" : "未锁定到定标商品，请检查参数是否正确"));

            CustomerOrderGoodsVo orderCustomerGoodsVO = new CustomerOrderGoodsVo();
            orderCustomerGoodsVO.setSku(orderGoodsSimple.getSku());
            orderCustomerGoodsVO.setCompany(orderGoodsSimple.getCompany());

            Map<String, Object> goodsPurchase = filterGoodsPurchaseList.get(0);
            orderCustomerGoodsVO.setGoods_src(goodsPurchase.get("type").equals(GoodsPurchaseTypeEnum.SINGLE) ? "2" : "3");
            //todo 报价商品id | 组织采购id？
            orderCustomerGoodsVO.setGoods_id(String.valueOf(goodsPurchase.get("quotation_goods_id")));
            orderCustomerGoodsVO.setNum(null != orderGoodsSimple.getQuantity() ? orderGoodsSimple.getQuantity() : BigDecimalUtils.integerToBigDecimal(goodsPurchase.get("num")));

            orderCustomerGoodsVO.setClient_order_goods_id(UUID.randomUUID().toString());

            orderCustomerGoodsVO.setPrice(orderGoodsSimple.getPrice());
            orderCustomerGoodsVO.setAmount(orderGoodsSimple.getAmount());
            //orderCustomerGoodsVO.setCompany(orderGoodsSimple.getCompany());
            orderCustomerGoodsVO.setWarehouse(orderGoodsSimple.getWarehouse());
            //orderCustomerGoodsVO.setRegion(String.valueOf(address.get("post")));
            String goodsExtendsAttr = OrderGoodsExtendsAttr.conversion(OrderGoodsExtendsAttr.builder()
                            .requisitioner(orderGoodsSimple.getRequisitioner())
                            .build(),
                    true);
            orderCustomerGoodsVO.setExtends_attr(goodsExtendsAttr);
            //todo orderCustomerGoodsVO.setWarehouse(orderGoodsSimple.getWarehouse());
            orderCustomerGoodsVOList.add(orderCustomerGoodsVO);
        }
        customerOrderVo.setCustomerOrderGoodsVo(orderCustomerGoodsVOList);
        return customerOrderVo;
    }

    @Override
    public Boolean getOrderGoods(String orderGoodsId, String s) {

        // 退款申请中 =》label：退款申请中（平台审批中） label
        Map<String, Object> customerOrderGoods = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS).selectField("*").eq("id", orderGoodsId).like("label", OrderApproveStatusEnum.REFUND_APPLICATION.id).queryForMap();

        return null != customerOrderGoods;
    }

    @Override
    public List<Map<String, Object>> applyRefund(ApplyRefundVo applyRefundVo) {
        if (null == applyRefundVo) {
            log.info("applyRefund 参数为空");
            return null;
        }
        BulkRefundVO bulkRefundVO = new BulkRefundVO();
        bulkRefundVO.setOrderGoodsId(applyRefundVo.getOrderGoodsId());
        bulkRefundVO.setNum(applyRefundVo.getNum());
        bulkRefundVO.setMemo(applyRefundVo.getMemo());
        //这个代码里面设计的有问题，这个amount其实最终里面没有用，是根据数量单价算出来的，但是代码里面加了这个还是必填的验证，所以就当没有这个amount不需要的
        bulkRefundVO.setAmount(BigDecimal.ONE);

        List<Map<String, Object>> results = orderService.applyRefund(Arrays.asList(bulkRefundVO));
        if (CollectionUtils.isNotEmpty(results)) {

            //todo 数据同步 publishEvent
//            applicationEventPublisher.publishEvent(new
//                    OrderRemoteSyncEvent(this, busProperties.getId(),
//                    "**", OrderRemoteSyncEventParam.builder()
//                    .type(OrderSyncEventTypeEnum.ApplyRefund).orderGoodsReturnsIds(results.stream().map(BaseEntity::getId).collect(Collectors.toList())).build()));
        }
        return results;
    }

    @Override
    public OrderSimpleResult buildOrderSimpleSuccessResult(IOrderCustomerVO iOrderCustomerVO) {

        if (iOrderCustomerVO == null) {
            return null;
        }
        List<OrderGoodsSimpleResult> orderGoodsResultList = new ArrayList<>();
        List<Map<String, Object>> vendorOrderGoodsList = JdbcTemplateUtils.builder(ModelConst.T_ORDER_VENDOR_GOODS).selectField("*").eq("order_customer_id", iOrderCustomerVO.getId()).queryForList();
        for (Map<String, Object> vendorOrderGoods : vendorOrderGoodsList) {
            orderGoodsResultList.add(OrderGoodsSimpleResult.builder().clientOrderGoodsId(String.valueOf(vendorOrderGoods.get("client_order_goods_id")))
                    .orderGoodsId(String.valueOf(vendorOrderGoods.get("id"))).build());
        }

        return OrderSimpleResult.builder()
                .clientOrderId(String.valueOf(iOrderCustomerVO.getClient_order_id()))
                .orderId(String.valueOf(iOrderCustomerVO.getId()))
                .orderGoodsResultList(orderGoodsResultList).build();
    }

    @Override
    public BigDecimal getOrderGoodsEnableNum(String orderGoodsId) {

        Map<String, Object> orderCustomerGoods = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS).selectField("*").eq("id", orderGoodsId).queryForMap();
        Assert.notNull(orderCustomerGoods, "未找到客户订单商品数据！！！");

        //select count(refund) from OrderGoodsRefundEntity refund where refund.del=false and refund.orderGoodsId in (?1) and refund.status <>5 and refund.status<>7
        //t_order_goods_returns
        List<Map<String, Object>> mapList = JdbcTemplateUtils.builder(ModelConst.T_ORDER_GOODS_RETURNS).selectField("*").eq("order_customer_goods_id", orderCustomerGoods.get("id"))
                .notEq("order_goods_returns_status", OrderGoodsReturnsStatusEnum.Done).queryForList();

        Assert.isTrue(CollectionUtils.isEmpty(mapList), "订单存在退款进行中的商品，需要退款结束才可收货");

        //已发数量

        List<Map<String, Object>> orderTraceList = JdbcTemplateUtils.builder(ModelConst.T_ORDER_TRACE).selectField("*").eq("order_customer_goods_id", orderCustomerGoods.get("id")).eq("type", TraceTypeEnum.ShippingLogistics.name()).queryForList();

        BigDecimal deliveredNum = BigDecimal.ZERO;
        if (!CollectionUtils.isEmpty(orderTraceList)) {
            for (Map<String, Object> orderTrace : orderTraceList) {
                if (null == orderTrace.get("quantity")) {
                    continue;
                }
                BigDecimal quantity = BigDecimalUtils.integerToBigDecimal(orderTrace.get("quantity"));
                deliveredNum = quantity.add(deliveredNum);
            }
        }

        //已收数量

        List<Map<String, Object>> orderGoodsAcceptList = JdbcTemplateUtils.builder(ModelConst.T_ORDER_GOODS_ACCEPT).selectField("*").eq("order_customer_goods_id", orderCustomerGoods.get("id")).queryForList();

        BigDecimal receivedNum = BigDecimal.ZERO;
        if (!CollectionUtils.isEmpty(orderGoodsAcceptList)) {
            for (Map<String, Object> orderGoodsAccept : orderGoodsAcceptList) {
                if (null == orderGoodsAccept.get("quantity")) {
                    continue;
                }
                BigDecimal quantity = BigDecimalUtils.integerToBigDecimal(orderGoodsAccept.get("quantity"));
                receivedNum = quantity.add(receivedNum);
            }
        }

        BigDecimal returnReceivedNum = BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("return_received_num"));
        BigDecimal returnedNum = BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("returned_num"));
        BigDecimal quantity = BigDecimalUtils.integerToBigDecimal(orderCustomerGoods.get("quantity"));
        //可收数量（已发数量-已收数量-已退货数量+退的收货的数量）
        BigDecimal enableNum = deliveredNum.subtract(receivedNum).subtract(returnedNum).add(returnReceivedNum);

        String errorMessage = "订单商品编号【" + orderCustomerGoods.get("id") + "】可收货数量【" + enableNum + "】必须";
        //如果可收货数量数量不等于订单总数量，需要判断是否存在已退数量
        if (enableNum.compareTo(quantity) != 0) {
            List<Map<String, Object>> orderGoodsRefundList = JdbcTemplateUtils.builder(ModelConst.T_ORDER_GOODS_RETURNS).
                    selectField("*").eq("order_customer_goods_id", orderCustomerGoods.get("id")).queryForList();
            BigDecimal refundQuantity = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(orderGoodsRefundList)) {
                for (Map<String, Object> orderGoodsRefund : orderGoodsRefundList) {
                    if (String.valueOf(orderGoodsRefund.get("order_goods_returns_status")).equals(OrderGoodsReturnsStatusEnum.Done)) {
                        BigDecimal num = BigDecimalUtils.integerToBigDecimal(orderGoodsRefund.get("quantity"));
                        refundQuantity = refundQuantity.add(num);
                    }
                }
            }
            //Double refundQuantity = this.verifyCompleteReceiveRefund(orderGoods.getId());
            BigDecimal subRefundGoodsQuantity = quantity.subtract(refundQuantity);
            //如果全退完，不可以影响收货，所以需要跳过
            if (subRefundGoodsQuantity.compareTo(BigDecimal.ZERO) == 0) {
                return BigDecimal.ZERO;
            }

            if (enableNum.compareTo(subRefundGoodsQuantity) != 0) {
                //兼容特殊情况在pm端部分收货
                subRefundGoodsQuantity = subRefundGoodsQuantity.subtract(receivedNum);
                Assert.isTrue(enableNum.compareTo(subRefundGoodsQuantity) == 0, errorMessage + "等于下单数量-已退数量【" + subRefundGoodsQuantity + "】");
            }
        }

        return enableNum;
    }

    /**
     * 根据公司获取固买仓库地址信息
     *
     * @param companyList 公司集合
     * @return 固买仓库地址信息，如果返回null表示非牧原下单，收货信息需要从参数带入，不需要从平台获取
     * Exception 牧原区域对照数据必须存在，并且多家公司必须对应唯一的区域，否则下单失败
     */
    private Map<String, Object> getDeliverAddressByCompany(String usserId, Set<String> companyList) {
        //获取当前用户组织信息
        List<UserDto> userList = UserUtils.getOrganizationUserByRoleName(usserId, PlatformConst.ROLE_CUSTOMER_COMPANY_REGION);
        Assert.isTrue(CollectionUtils.isNotEmpty(userList), "未获取到角色ROLE_CUSTOMER_COMPANY_REGION的用户");
        //查询会员收货地址
        List<Map<String, Object>> deliverAddressList = JdbcTemplateUtils.builder(AppConst.PERSONAL_CENTER, ModelConst.T_MEMBER_DELIVER_ADDRESS).selectField("*").eq("member_id -> '$.id'", userList.get(0).getId())
                .in("alias", companyList).queryForList();

        Assert.isTrue(CollectionUtils.isNotEmpty(deliverAddressList), "请维护公司区域对照表信息");
        Assert.isTrue(deliverAddressList.stream().map(t -> String.valueOf(t.get("post")).trim()).distinct().count() == 1, "根据公司获取区域必须唯一");
        //拿到最新的地址
        return deliverAddressList.stream().max(Comparator.comparing(e -> String.valueOf(e.get("id")))).get();
    }

    private void checkOrder(OrderCustomerVO customerOrder) {

        Assert.isTrue(null != customerOrder, "客户订单数据错误！");

        Assert.isTrue(CollectionUtils.isNotEmpty(customerOrder.getOrderVendorVOList()), "供应商订单数据错误！");

        Assert.isTrue(StringUtils.isNotBlank(customerOrder.getAddress()) || StringUtils.between(customerOrder.getAddress(), 0, 500), "客户订单地址为空！");

        Assert.isTrue(StringUtils.isNotBlank(customerOrder.getPhone()) || StringUtils.between(customerOrder.getPhone(), 0, 50), "客户订单电话为空！");

        Assert.isTrue(StringUtils.isNotBlank(customerOrder.getReceiver()) || StringUtils.between(customerOrder.getReceiver(), 0, 50), "收货人为空！");

        if (null == customerOrder.getPostal()) {
            customerOrder.setPostal("");
        }
        if (null == customerOrder.getErp_po()) {
            customerOrder.setErp_po("");
        }
        if (null == customerOrder.getClient_id()) {
            customerOrder.setClient_id("");
        }

        if (null == customerOrder.getPlace_order_user_id()) {
            customerOrder.setPlace_order_user_id(null);
        }

        if (null == customerOrder.getClient_order_id()) {
            customerOrder.setClient_order_id("");
        }
    }

    /**
     * 获取表名称
     *
     * @param schemaCode
     * @return
     */
    public String getTableName(String schemaCode) {
        return tableHelper.getTableName(schemaCode);
    }


}
